import net from'net';
import { Buffer } from'buffer';

export  function sendjson(data,ip='127.0.0.1', port=3473) {
    return new Promise((resolve, reject) => {
        const client = new net.Socket();
        client.setTimeout(30000);
        client.on('error', (err) => {
            client.destroy();
            reject(err);
        });
        client.on('timeout', () => {
            client.destroy();
            reject(new Error('Connection timeout'));
        });
        client.connect(port, ip, () => {
            try {
                const jsonStr = JSON.stringify(data);
                const dataBuffer = Buffer.from(jsonStr, 'utf-8');
                const header = Buffer.alloc(4);
                header.writeUInt32BE(dataBuffer.length, 0);
                client.write(Buffer.concat([header, dataBuffer]));
            } catch (err) {
                client.destroy();
                reject(err);
            }
        });
        let receivedHeader = false;
        let expectedLength = 0;
        let chunks = [];
        let received = 0;
        client.on('data', (chunk) => {
            if (!receivedHeader) {
                if (chunk.length < 4) {
                    chunks.push(chunk);
                    return;
                }
                const header = Buffer.concat([...chunks, chunk]).subarray(0, 4);
                expectedLength = header.readUInt32BE(0);
                chunks = [chunk.subarray(4)];
                received = chunks[0].length;
                receivedHeader = true;
            } else {
                chunks.push(chunk);
                received += chunk.length;
            }
            if (received >= expectedLength) {
                const fullData = Buffer.concat(chunks).subarray(0, expectedLength);
                client.destroy();
                
                try {
                    resolve(JSON.parse(fullData.toString('utf-8')));
                } catch (err) {
                    reject(new Error('Invalid JSON response'));
                }
            }
        });
        client.on('close', () => {
            if (!receivedHeader || received < expectedLength) {
                reject(new Error('Connection closed prematurely'));
            }
        });
    });
}

(async () => {
    try {
        const response = await sendjson( {
            message: "Hello from Node.js",
            timestamp: Date.now()
        });
        console.log('Server response:', response);
    } catch (err) {
        console.error('Error:', err.message);
    }
})();